package service.impl;

import dao.Impl.UserImpl;
import dao.UserDao;
import dto.UserModelDto;
import model.ResultModel;
import model.UserModel;
import service.IUserService;

public class UserServiceImpl implements IUserService {

    @Override
    public int add(UserModel userModel) {
        UserDao dao = new UserImpl();
        if (findByName(userModel.getUsername()) == null) {
            return dao.add(userModel);
        }
        return 0;
    }

    @Override
    public ResultModel loginResult(UserModelDto userModelDto) {
        ResultModel resultModel = new ResultModel();
        if (!userModelDto.getCode().equals(userModelDto.getsCOde())) {
            resultModel.setCode("400");
            resultModel.setResult("验证码不正确，请重新输入");
        } else {
            //验证账号密码是否正确
            UserModel userModel = new UserModel();
            userModel.setUsername(userModelDto.getUsername());
            userModel.setPassword(userModelDto.getPassword());
            if (findByUsernameAndPassword(userModel) == null) {
                //==null代表用户名不存在或者用户名和密码输入错误
                resultModel.setCode("400");
                resultModel.setResult("登录失败，请重新输入");

            } else {
                resultModel.setCode("200");
                resultModel.setResult("登录成功，即将跳转到管理页面");
            }
        }
        return resultModel;
    }

    public UserModel findByUsernameAndPassword(UserModel userModel) {
        UserDao dao =new UserImpl();
        return dao.findByUsernameAndPassword(userModel);
    }

    public UserModel findByName(String username) {
        UserDao dao = new UserImpl();
        return dao.findByName(username);
    }
}
